package com.svpino.netflix.parsers;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.svpino.netflix.Proxy;
import com.svpino.netflix.model.Catalog;
import com.svpino.netflix.model.CatalogItem;

public class CatalogParser extends AbstractParser<Catalog> {

	public CatalogParser(Proxy proxy) {
		super(proxy);
	}

	public Catalog parse(String resource) throws Exception {
		return parse(request(resource));
	}

	@Override
	public Catalog parse(Element element) throws Exception {
		List<CatalogItem> catalogItems = new ArrayList<CatalogItem>();

		XPathFactory factory = XPathFactory.newInstance();
		XPath xPath = factory.newXPath();
		XPathExpression maturityLevelXPathExpression = xPath.compile("./category[@scheme='http://api.netflix.com/categories/maturity_level']");

		NodeList nodeList = element.getElementsByTagName("catalog_title");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element catalogItemElement = (Element) nodeList.item(i);

			String id = ((Element) catalogItemElement.getElementsByTagName("id").item(0)).getTextContent();
			Element titleElement = (Element) catalogItemElement.getElementsByTagName("title").item(0);

			String regularTitle = titleElement.getAttribute("regular");

			Element releaseYearElement = (Element) catalogItemElement.getElementsByTagName("release_year").item(0);
			int releaseYear = Integer.parseInt(releaseYearElement.getTextContent());

			Element ratingElement = (Element) catalogItemElement.getElementsByTagName("average_rating").item(0);
			float rating = Float.parseFloat(ratingElement.getTextContent());

			Element maturityLevelElement = (Element) maturityLevelXPathExpression.evaluate(catalogItemElement, XPathConstants.NODE);
			Integer maturityLevel = maturityLevelElement != null ? Integer.parseInt(maturityLevelElement.getAttribute("term")) : null;

			CatalogItem title = new CatalogItem(
					getProxy(),
					id,
					regularTitle,
					releaseYear,
					rating,
					maturityLevel,
					catalogItemElement);

			catalogItems.add(title);
		}

		return new Catalog(10, 10, catalogItems);
	}

}
